import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import ContainerView from '../views/ContainerView.vue'
import isLogin from '@/utils/login.js'

const vueRouterObj = {
  //history：你使用 的是hash模式还是history模式  ;
  history: createWebHashHistory(import.meta.env.BASE_URL),
  //路由表
  routes: [
    {
      path: '/',
      // alias：该页面的另一个访问路由
      alias: '/home',
      // 重定向，一般不设置在这
      // redirect:'/contain',
      name: 'home',
      component: HomeView

      //路由守卫
    },
    {
      path: '/user/:id/:username',
      name: 'user',
      //懒加载路由
      // props为一个布尔值的情况下，自动获取id到script的defineProps中
      // props:true,

      //props是一个对象的时候,不能将id传过去
      // props:{name:'zp',age:10},

      // 函数传递
      props: route => ({ name: 'zp', age: 10, id: route.params.id, username: route.params.username }),
      //需不需登陆验证
      meta: { requiresLogin: true },
      component: () => import('../views/AboutView.vue'),
      /* beforeEnter: (to, from, next) => {
        // ...
        if (!isLogin()) {
          //，有授权，没有登陆
          // next();
          next('/home');
        }
        next();
      } */
    },
    //嵌套路由
    {
      path: '/contain',
      name: 'contain',
      component: ContainerView,
      children: [
        {
          path: '/contain/about',
          name: 'cabout',
          // 组件  懒加载
          component: () => import('../views/AboutView.vue')
        },
        {
          path: '/contain/home',
          name: 'chome',
          component: HomeView
        }
      ]
    }

  ]
}

//1.创建路由对象
const router = createRouter(vueRouterObj)

//全局守卫
/* router.beforeEach((to,from,next)=>{
  if(to.meta.requiresLogin && isLogin()){
    //有登陆，有授权
    next();
  }else{
    //没登录
    next('/home');
  }
}) */

/* router.beforeEach((to, from, next) => {
  //去遍历每个路由的meta有没有requiresLogin授权

  if (to.meta.requiresLogin && !isLogin()) {
    //，有授权，没有登陆
    // next();
    next('/home');
  }

  next();
}) */

export default router
